import jwt from 'jsonwebtoken';
import Result from './result.js';
import 'dotenv/config';

// Secret key for JWT
const secretKey = process.env.JWT_SECRET_KEY; 

// Routes that don't require authentication
const publicRoutes = [
  '/api/login', 
  '/api/register',
  '/api/check-email'
];  

export const authenticateToken = (req, res, next) => {
  console.log(req.originalUrl);
  const token = req.headers['authorization'];

  // Skip authentication for public routes or non-api routes
  if (publicRoutes.includes(req.originalUrl) || !req.originalUrl.startsWith('/api')) {
    return next();
  }

  if (!token) {
    return Result.error(res, Result.ACCESS_DENIED_MESSAGE, Result.ACCESS_DENIED_CODE)
  }

  try {
    const decoded = jwt.verify(token, secretKey);
    req.studentId = decoded.id;
    next()
  } catch (err) {
    return Result.error(res, Result.INVALID_TOKEN_MESSAGE, Result.INVALID_TOKEN_CODE)
  }
};

export const generateToken = (id, name, email) => {
  return jwt.sign({ id, name, email }, secretKey, { expiresIn: '1h' });
};

export const getTokenInfo = (token) => {
  const decoded = jwt.decode(token);
  if (!decoded) {
    return Result.error(res, Result.INVALID_TOKEN_MESSAGE, Result.INVALID_TOKEN_CODE)
  }
  return decoded;
};
